﻿using System;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Windows.Forms;
using NetFwTypeLib;
using WUTOS.DataBase.DataBaseDAL;

namespace WUTOS.DataBase
{
    public partial class PeripheralConfigFrame : Form
    {
        #region Parameters

        //Get local sqlservices
        private List<ServiceController> serivController = null;

        //sqlserver service name
        private static string servicName = string.Empty;

        //sqlbroswer service name
        private static string browserName = string.Empty;

        //firewall
        private DataBaseDAL.FireWallControl fireControl = null;

        //数据库版本及身份验证模式
        List<BLL.databaseversion> databaseVersion = BLL.GetLocalDataBaseVersion();

        #endregion

        public PeripheralConfigFrame()
        {
            InitializeComponent();
            serivController = new List<ServiceController>();
            fireControl = new DataBaseDAL.FireWallControl();
        }

        private void PeripheralConfigFrame_Load(object sender, EventArgs e)
        {
            InitialServicesList();
        }

        #region 初始化数据 界面操作
        
        /// <summary>
        /// 初始化控件 绑定数据
        /// </summary>
        private void InitialServicesList()
        {
            ClearControl();
            DataBaseDAL.BLL.GetSqlServerServiceName(serivController);
            fireControl.Initialize();

            List<string> dbVersion = new List<string>();
            foreach (BLL.databaseversion Version in databaseVersion)
            {
                dbVersion.Add(Version.version);
            }
            cbRemotServerName.DataSource = dbVersion;


            foreach (ServiceController serCon in serivController)
            {
                if (serCon.ServiceName=="SQLBrowser")
                {
                    this.cbBrowserName.Items.Add(serCon.ServiceName);
                }
                else
                {
                    this.cbServerName.Items.Add(serCon.ServiceName);
                }
            }

            if (this.cbServerName.Items.Count>0)
            {
                this.cbServerName.Text = servicName;
            }

            if (this.cbBrowserName.Items.Count>0)
            {
                this.cbBrowserName.Text = browserName;
            }
        }

        /// <summary>
        /// 清除控件信息
        /// </summary>
        private void ClearControl()
        {
            serivController.Clear();
            cbServerName.Items.Clear();
            cbBrowserName.Items.Clear();
            tbBrowserShowName.Clear();
            tbBrowserDetail.Clear();
            tbBrowserState.Clear();
            tbServiceDetail.Clear();
            tbServiceState.Clear();
            tbServiceServerShowName.Clear();
        }

        #endregion

        #region  数据库服务配置
        /// <summary>
        /// 判断服务器名称
        /// </summary>
        /// <returns></returns>
        private bool ValidateInput()
        {
            if (String.IsNullOrEmpty(this.cbRemotServerName.Text))
            {
                this.erProvide.SetError(this.cbRemotServerName, "请选服务器名称！");
                this.ActiveControl = cbRemotServerName;
                return false;
            }
            return true;
        }

        /// <summary>
        ///  服务tab 服务名改变切换数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbServerName_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.erProvide.Clear();
            servicName = this.cbServerName.Text;
            DataBaseDAL.ServiceControllerEx scEx = new DataBaseDAL.ServiceControllerEx(this.cbServerName.Text);
            this.tbServiceServerShowName.Text = scEx.DisplayName;
            this.tbServiceDetail.Text = scEx.Description;
            this.cbServiceStartType.Text = scEx.StartupType;
            this.tbServiceState.Text = DataBaseDAL.BLL.GetServiceState(scEx);
        }

        private void cbmServiceStartType_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.erProvide.Clear();
        }


        /// <summary>
        /// 启动服务 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btServicesStart_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.cbServerName.Text))
            {
                this.erProvide.SetError(this.cbServerName, "请选择服务器名称！");
                this.ActiveControl = this.cbServerName;
                return;
            }

            DataBaseDAL.ServiceControllerEx scEx = new DataBaseDAL.ServiceControllerEx(this.cbServerName.Text);
            if (scEx.Status == ServiceControllerStatus.Stopped)
            {
               if (DataBaseDAL.BLL.GetServiceStartType(ref scEx)!=3)
                {
                    try
                    {
                        this.Cursor = Cursors.WaitCursor;
                        scEx.Start();
                        scEx.WaitForStatus(ServiceControllerStatus.Running);
                        InitialServicesList();
                        this.Cursor = Cursors.Arrow;
                        MessageBox.Show(this.cbServerName.Text+"服务启动成功！","系统提示",
                                          MessageBoxButtons.OK,MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
                else
                {
                    this.erProvide.SetError(cbServiceStartType, "Disable条件下禁止启动服务\r\n必须手动设置为Auto或Manual");
                    this.ActiveControl = cbServiceStartType;
                }
            }
        }

        /// <summary>
        /// 停止服务 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btServicesStop_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.cbServerName.Text))
            {
                this.erProvide.SetError(this.cbServerName, "请选择服务器名称！");
                this.ActiveControl = this.cbServerName;
                return;
            }

            DataBaseDAL.ServiceControllerEx scEx = new DataBaseDAL.ServiceControllerEx(cbServerName.Text);
            if (scEx.Status == ServiceControllerStatus.Running)
            {
                this.Cursor = Cursors.WaitCursor;
                scEx.Stop();
                scEx.WaitForStatus(ServiceControllerStatus.Stopped);
                MessageBox.Show(this.cbServerName.Text + "服务已停止！", "系统提示",
                                       MessageBoxButtons.OK, MessageBoxIcon.Information);
                InitialServicesList();
                this.Cursor = Cursors.Arrow;
            }
        }

        /// <summary>
        /// 应用服务操作类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btServiceApplay_Click(object sender, EventArgs e)
        {
            if (this.cbServerName.Text != null && !String.IsNullOrEmpty(this.cbServerName.Text))
            {
                if (cbServiceStartType.Text != null && !String.IsNullOrEmpty(this.cbServiceStartType.Text))
                {
                    this.Cursor = Cursors.WaitCursor;
                    DataBaseDAL.ServiceControllerEx scEx = new DataBaseDAL.ServiceControllerEx(this.cbServerName.Text);
                    DataBaseDAL.BLL.GetServiceStartType(this.cbServiceStartType.Text, ref scEx);
                    InitialServicesList();
                    this.Cursor = Cursors.Arrow;
                    MessageBox.Show(this.cbServerName.Text + "服务器" + "启动类型" + this.cbServiceStartType.Text + "设置成功！", "系统提示",
                                   MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    this.erProvide.SetError(this.cbServiceStartType, "请选择服务类型名！");
                    this.ActiveControl = this.cbServiceStartType;
                }
            }
            else
            {
                this.erProvide.SetError(this.cbServerName, "请选择服务名！");
                this.ActiveControl = this.cbServerName;
            }
        }

        #endregion

        #region sqlBrowser服务配置 
        
    
        /// <summary>
        /// sqlBroswer服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbBrowserName_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.erProvide.Clear();
            browserName = this.cbBrowserName.Text;
            DataBaseDAL.ServiceControllerEx scEx = new DataBaseDAL.ServiceControllerEx(this.cbBrowserName.Text);
            this.tbBrowserShowName.Text = scEx.DisplayName;
            this.tbBrowserDetail.Text=scEx.Description;
            this.cbBrowserStartType.Text=scEx.StartupType;
            this.tbBrowserState.Text = DataBaseDAL.BLL.GetServiceState(scEx);
        }

        /// <summary>
        /// sqlBroswer服务启用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btBrowserStart_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.cbBrowserName.Text))
            {
                this.erProvide.SetError(this.cbBrowserName, "请选择服务器名称！");
                this.ActiveControl = this.cbBrowserName;
                return;
            }

            DataBaseDAL.ServiceControllerEx scEx = new DataBaseDAL.ServiceControllerEx(this.cbBrowserName.Text);
            if (scEx.Status == ServiceControllerStatus.Stopped)
            {
                if (DataBaseDAL.BLL.GetServiceStartType(ref scEx) != 3)
                {
                    try
                    {
                        this.Cursor = Cursors.WaitCursor;
                        scEx.Start();
                        scEx.WaitForStatus(ServiceControllerStatus.Running);
                        InitialServicesList();
                        this.Cursor = Cursors.Arrow;
                        MessageBox.Show(this.cbBrowserName.Text + "服务启动成功！", "系统提示",
                                         MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                }
                else
                {
                    this.erProvide.SetError(cbBrowserStartType, "Disable条件下禁止启动服务\r\n必须手动设置为Auto或Manual");
                    this.ActiveControl = cbBrowserStartType;
                }
            }
        }

        /// <summary>
        /// sqlBroswer停用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbBrowserStop_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.cbBrowserName.Text))
            {
                this.erProvide.SetError(this.cbBrowserName, "请选择服务器名称！");
                this.ActiveControl = this.cbBrowserName;
                return;
            }
            DataBaseDAL.ServiceControllerEx scEx = new DataBaseDAL.ServiceControllerEx(this.cbBrowserName.Text);
            if (scEx.Status == ServiceControllerStatus.Running)
            {
                this.Cursor = Cursors.WaitCursor;
                scEx.Stop();
                scEx.WaitForStatus(ServiceControllerStatus.Stopped);
                InitialServicesList();
                this.Cursor = Cursors.Arrow;
                MessageBox.Show(this.cbBrowserName.Text + "服务已停止！", "系统提示",
                                     MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// sqlBroswer启动类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbBroswerApplay_Click(object sender, EventArgs e)
        {
            if (this.cbBrowserName.Text != null && !String.IsNullOrEmpty(this.cbBrowserName.Text))
            {
                if (cbBrowserStartType.Text != null && !String.IsNullOrEmpty(this.cbBrowserStartType.Text))
                {
                    this.Cursor = Cursors.WaitCursor;
                    DataBaseDAL.ServiceControllerEx scEx = new DataBaseDAL.ServiceControllerEx(this.cbBrowserName.Text);
                    DataBaseDAL.BLL.GetServiceStartType(this.cbBrowserStartType.Text, ref scEx);
                    InitialServicesList();
                    this.Cursor = Cursors.Arrow;
                    MessageBox.Show(this.cbBrowserName.Text + "服务器" + "启动类型" + this.cbBrowserStartType.Text + "设置成功！", "系统提示",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    this.erProvide.SetError(this.cbBrowserStartType, "请选择服务类型名！");
                    this.ActiveControl = this.cbBrowserStartType;
                }
            }
            else
            {
                this.erProvide.SetError(this.cbBrowserName, "请选择服务名！");
                this.ActiveControl = this.cbBrowserName;
            }
        }


        #endregion

        #region FireWall 配置
        
     

        /// <summary>
        /// 打开浏览 添加例外程序 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btFileBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "应用程序(*.exe;*.com,*.icd)|*.exe|所有程序|*.*";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string fileName = string.Empty; 
                try
                {
                    this.tbFilePath.Text = dlg.FileName;
                    fileName = System.IO.Path.GetFileNameWithoutExtension(dlg.FileName);
                    fireControl.AddApplication(dlg.FileName, fileName);
                    MessageBox.Show(fileName + ".exe" + "添加成功！", "系统提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                  MessageBox.Show(fileName+".exe"+"添加失败！","系统提示",
                       MessageBoxButtons.OK,MessageBoxIcon.Warning);
                  return;
                }
            }
        }

        /// <summary>
        /// 添加端口配置
        /// </summary>
        /// <returns></returns>
        private bool ValicateInputPortInfor()
        {
            if (string.IsNullOrEmpty(this.tbAddPortName.Text))
            {
                this.erProvide.SetError(this.tbAddPortName, "请请入添加端口名称！");
                this.ActiveControl = this.tbAddPortName;
                return false;
            }

            if (string.IsNullOrEmpty(this.tbAddPort.Text))
            {
                this.erProvide.SetError(this.tbAddPort, "请请入添加端口号！");
                this.ActiveControl = this.tbAddPort;
                return false;
            }

            if (!System.Text.RegularExpressions.Regex.IsMatch(this.tbAddPort.Text, @"^[1-9]$|(^[1-9][0-9]$)|(^[1-9][0-9][0-9]$)|(^[1-9][0-9][0-9][0-9]$)|(^[1-6][0-5][0-5][0-3][0-5]$)"))
            {
                this.erProvide.SetError(this.tbAddPort, "端口号填写错误(0-65535)！");
                this.ActiveControl = this.tbAddPort;
                return false;
            }
            return true;
        }


        /// <summary>
        /// 添加端口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAddPort_Click(object sender, EventArgs e)
        {
            this.erProvide.Clear();
            if (ValicateInputPortInfor())
            {
                try
                {

                    if (rbTcp.Checked)
                    {
                        fireControl.AddPort(Convert.ToInt32(this.tbAddPort.Text),
                                           NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP,
                                           this.tbAddPortName.Text.Trim());
                    }
                    else
                    {
                        fireControl.AddPort(Convert.ToInt32(this.tbAddPort.Text),
                                    NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP,
                                    this.tbAddPortName.Text.Trim());
                    }
                    this.tbAddPort.Clear();
                    this.tbAddPortName.Clear();
                    MessageBox.Show(this.tbAddPort.Text + "端口" + "添加成功！", "系统提示",
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this.tbAddPort.Text + "端口" + "添加失败！", "系统提示",
                                     MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btCancelPort_Click(object sender, EventArgs e)
        {
            this.tbAddPort.Clear();
            this.tbAddPortName.Clear();
            this.erProvide.Clear();
            this.Close();
        }

        #endregion

        #region 通信协议配置 tcp/ip np

        /// <summary>
        /// 应用 tcp np协议 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btRemotApply_Click(object sender, EventArgs e)
        {
            if (ValidateInput())
            {
                int tcpKey = 0;
                int npKey = 0;
                if (cbTcpIp.Checked)
                {
                    tcpKey = 1;
                }

                if (cbNamePipes.Checked)
                {
                    npKey = 1;
                }
                DataBaseDAL.BLL.SetRemotConnection(this.cbRemotServerName.Text, tcpKey, npKey);
                MessageBox.Show("协议设置成功！","系统提示",
                    MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 根据服务器查找当前协议状态 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbRemotServerName_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbTcpIp.Checked = false;
            cbNamePipes.Checked = false;
            string serName = BLL.SearchStringLocalDbList(this.cbRemotServerName.Text);
            if (string.IsNullOrEmpty(serName))
            {
                return;
            }
            int tcpEnable = 0;
            int udpEnable = 0;
            DataBaseDAL.BLL.GetRemotConnection(serName, ref tcpEnable, ref udpEnable);
            if (tcpEnable == 1)
            {
                cbTcpIp.Checked = true;
            }
            if (udpEnable == 1)
            {
                cbNamePipes.Checked = true;
            }
        }

        /// <summary>
        /// 取消通信协议设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btRemotCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion 
    }
}
